package cn.zifangsky.random.questions;

import org.junit.Test;

import java.util.Arrays;
import java.util.Random;

/**
 * 洗牌
 *
 * @author zifangsky
 * @date 2020/5/11
 * @since 1.0.0
 */
public class Problem_002_Shuffle {
    /**
     * 测试代码
     */
    @Test
    public void testMethods(){
        int[] arr = new int[15];

        for (int i = 0; i < arr.length; i++){
            arr[i] = i;
        }

        //洗牌
        shuffle(arr);
        System.out.println(Arrays.toString(arr));
    }

    /**
     * 洗牌
     */
    private void shuffle(int[] arr){
        if(arr == null || arr.length < 1){
            return;
        }
        Random rnd = new Random();

        for(int i = (arr.length -1); i > 0; i--){
            swap(arr, i, rnd.nextInt(i));
        }
    }

    private void swap(int[] arr, int i, int j){
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}
